# This code is part of the MWP System
# Copyright (c) 2012 Benjamin Lubin (blubin@bu.com) 
# Published under and subject to the GPLv2 license available at http://www.gnu.org/licenses/gpl-2.0.html

'''
Created on Dec 13, 2012
@author: blubin
'''

from backend.backend import Backend;
from workflow.task import Task;
from workflow.result import Result;
from workflow.flowData import Status;

class PuppyBackend(Backend):
   
    def __init__(self): 
        Backend.__init__(self, "PuppyService3", dashboard=True);

    def wire(self):
        self.register_result_listener("Customer", "CallRequest", self.call_request_complete)
        self.register_result_listener("Administrator", "ConfirmRequest", self.confirm_request_complete)
        self.register_result_listener("Trainer", "ReceiveSchedule", self.receive_schedule_complete)
        self.register_result_listener("Administrator", "CollectPayment", self.collect_payment_complete)


    def call_request_complete(self, results):
        for result in results:
            task = Task.construct_from_result(result, "Administrator", "ConfirmRequest");
            self.workflow.add(task);
            self.workflow.update_status(result, Status.COMPLETE);

    def confirm_request_complete(self, results):
        for result in results:
            if result.data['timeavailable'] == "TRUE":
                #Add task to write the needed prescription
                task = Task.construct_from_result(result, "Trainer", "ReceiveSchedule");
                self.workflow.add(task);
                self.workflow.update_status(result, Status.COMPLETE);
            else:
                task = Task.construct_from_result(result, "Customer", "CallRequest");
                if 'callrequestnumber' in result.data:
                    task.set_field('callrequestnumber',result.get_int_field('callrequestnumber')+1);
                else:
                    task.set_field('callrequestnumber',0)
                self.workflow.add(task);
                self.workflow.update_status(result, Status.COMPLETE);
                            
    def receive_schedule_complete(self, results):
        for result in results:
            if result.data['dogsletoutandreturned'] == "TRUE":
                task = Task.construct_from_result(result, "Administrator", "CollectPayment");
                self.workflow.add(task);
                self.workflow.update_status(result, Status.COMPLETE);

    def collect_payment_complete(self, results):
        for result in results:
            self.workflow.update_status(result, Status.COMPLETE);

if __name__ == '__main__':
    backend = PuppyBackend();